package com.lx.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.lx.common.lang.Result;
import com.lx.entity.User;
import com.lx.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 零限Lx
 * @since 2022-10-25
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        // 根据用户名查询用户
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StringUtils.isNotBlank(user.getUsername()), User::getUsername, user.getUsername());
        User getUser = userService.getOne(lqw);
        if (getUser == null) {
            return Result.fail("该用户不存在");
        }
        if (!getUser.getPassword().equals(user.getPassword())) {
            return Result.fail("密码错误");
        }
        return Result.success(getUser);
    }

    @GetMapping("/getUser/{id}")
    public Result getUser(@PathVariable String id) {
        User user = userService.getById(id);
        return Result.success(user);
    }

    @PostMapping("/update")
    public Result update(@RequestBody User user) {
        System.out.println(user);
        userService.updateById(user);
        return Result.success();
    }

    /**
     * 上传接口
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public Result upload(@RequestBody MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String flag = IdUtil.fastSimpleUUID();
        String filePath = System.getProperty("user.dir") + "/springboot-demo01/src/main/resources/files/" + flag + "_" + originalFilename; // 1.修改子模块路径
        FileUtil.writeBytes(file.getBytes(), filePath);
        return Result.success("http://localhost:80/user/" + flag); // 2.返回下载文件的url
    }

    /**
     * 下载接口
     * @param flag
     * @param response
     */
    @GetMapping("/{flag}")
    public void getFiles(@PathVariable String flag, HttpServletResponse response) {
        OutputStream os;  // 新建一个输出流对象
        String basePath = System.getProperty("user.dir") + "/springboot-demo01/src/main/resources/files/";  // 定于文件上传的根路径 // 1.文件所在目录
        List<String> fileNames = FileUtil.listFileNames(basePath);  // 获取所有的文件名称
        String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");  // 找到跟参数一致的文件
        try {
            if (StrUtil.isNotEmpty(fileName)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(basePath + fileName);  // 通过文件的路径读取文件字节流
                os = response.getOutputStream();   // 通过输出流返回文件
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            System.out.println("文件下载失败");
        }
    }

}
